let layer = layui.layer;
let form = layui.form;
// 数据太多，需要就一下
let query = {
  sex: "",
  username: "",
  mobile: "",
  page: 1,
  limit: 10,
};

// 渲染列表
async function getList() {
  const {
    data: {
      data: { data, count, currentPage, totalPage, pageSize },
    },
  } = await axios.get("/ydd_user/list", { params: query });

  // 分页效果
  layui.use("laypage", function () {
    let laypage = layui.laypage;

    //执行一个laypage实例
    laypage.render({
      elem: "page-box", //注意，这里的 test1 是 ID，不用加 # 号
      count: count, //数据总数，从服务端得到

      // *这个保证不会切换内容但是页码还在第一页
      curr: query.page, // 数据起始页 决定那个按钮高亮

      limit: query.limit, // 每页显示多少条
      layout: ["count", "limit", "prev", "page", "next", "skip"],
      limits: [10, 20, 30, 40, 50, 100],

      // 点击分页
      jump: function (obj, first) {
        // jump触发机制有两种情况
        // 1.分页渲染时也会触发
        // 2.分页切换时会触发该函数

        //obj包含了当前分页的所有参数，比如：
        // ! 记得修改query对象
        query.page = obj.curr; //得到当前页，以便向服务端请求对应页的数据。
        query.limit = obj.limit; //得到每页显示的条数
        // getList()
        //首次不执行
        if (!first) {
          getList();
        }
      },
    });
  });

  // 遍历数组，把数据渲染进去
  const newArr = data
    .map((item, index) => {
      const gender = item.sex === 0 ? "男" : "女";
      const bday = item.birthday === null ? "" : item.birthday;
      const img = item.icon === null ? "" : item.icon;
      return `
    <tr>
      <td>${index + 1}</td>
      <td>${item.id}</td>
      <td>${item.username}</td>
      <td>${item.mobile}</td>
      <td><img src="${
        "http://124.223.14.236:8060" + img
          ? "http://124.223.14.236:8060" + img
          : ""
      }" alt=""></td>
      <td><span class="sex">${gender}</span></td>
      <td>${bday}</td>
      <td>
      <button class="layui-icon layui-icon-edit" id="bj" data-id="${
        item.id
      }"></button>
      <button class="layui-icon layui-icon-delete" id="lj" data-id="${
        item.id
      }"></button>
      </td>
    </tr>
    `;
    })
    .join("");
  document.querySelector("#list").innerHTML = newArr;
}
getList();

// 点击搜索重置功能
function build() {
  // 点击搜索功能
  document.querySelector("#search").addEventListener("click", function () {
    const username = document.querySelector("#lsc-username").value;
    const phone = document.querySelector("#lsc-pho").value;
    const sex = document.querySelector("#lsc-sex").value;
    if (username === "" && phone === "" && sex === "") {
      return alert("请输入数据");
    }
    query.username = username;
    query.sex = sex;
    query.mobile = phone;
    getList();
  });

  // 点击重置功能
  document.querySelector("#lsc-reset").addEventListener("click", function () {
    document.querySelector("#lsc-username").value = "";
    document.querySelector("#lsc-pho").value = "";
    document.querySelector("#lsc-sex").value = "";
    query.username = "";
    query.sex = "";
    query.mobile = "";
    getList();
  });
}
build();



// 定义编辑弹框
const css = `
<form class="layui-form" id="form-edit" lay-filter="form-edit">
  <!-- 隐藏域，保存 Id 的值 -->
      <input type="hidden" name="id">
        <div class="diviputt">
          <div class="layui-form-item" style="float: left;">
            <label class="layui-form-label" style="margin-top: 25px;">*用户名</label>
            <div class="layui-input-block">
              <input type="text" name="username" required lay-verify="required"
                placeholder="请输入用户名称" autocomplete="off" class="layui-input" style="width: 250px;height: 36px;margin-top: 25px;">
            </div>
          </div>
          <div class="layui-form-item" style="float: right;">
            <label class="layui-form-label" style="margin-top: -54px;">*手机号</label>
            <div class="layui-input-block">
              <input type="text" name="mobile" required lay-verify="required"
              placeholder="请输入手机号名称" autocomplete="off" class="layui-input" style="width: 250px;height: 36px;margin-top: -54px; margin-right: 30px;">
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">密码</label>
          <div class="layui-input-block">
            <input type="text" name="password" 
              placeholder="留空表示不修改" autocomplete="off" class="layui-input" style="width: 250px;height: 36px;">
          </div>
        </div>
        <div class="layui-form-item" pane="">
          <label class="layui-form-label">*性别</label>
          <input type="text" name="sex1" value="0" style="display: none;">
          <div class="layui-input-block">
            男
            <input id="switchTest" type="checkbox" name="sex" value="0" lay-skin="switch" lay-filter="switchTest" title="开关">
            女
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label" style="margin-top: 15px;">用户头像</label>
          <div class="layui-input-block">
            <input type="file" id="file" style="display: none;" accept="image/jpeg,image/png,image/gif,image/bmp"/> 
            <div class="lsc-box layui-input-block" name="icon" style="width: 300px;height: 92px;display: none;">
              <img src="" class="layui-input" id="lsc-img" alt="" style="width: 50%;height: 100%;">
            </div>
            <button class="layui-btn layui-btn-normal"  style="margin-top: 18px;" id="changMsg">点击上传
            </button>
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-input-block" style="margin-left: 630px;margin-top: 40px;">
          <button type="button" class="layui-btn layui-btn-primary" lay-submit lay-filter="formDemo" id="lsc-close">取消</button>
          <button type="button" class="layui-btn layui-btn-normal" lay-submit lay-filter="formDemo"> 确定</button>
          </div>
        </div>
    </form>
`

// 编辑删除功能
let indexEdit;
function fix() {
  // 定义一个变量储存图片数据
  let lscimg
  $(".lsc-list").on("click", async function (e) {
    // console.log(e.target.id)
    const id = e.target.dataset.id;
    if (e.target.id === "bj") {
      // 弹出编辑层
      indexEdit = layer.open({
        type: 1,
        area: ["800px", "380px"],
        title: "修改用户",
        content: css,
      });

      // 发送axios请求获取数据并且渲染到弹出层
      const {
        data: { data },
      } = await axios.get("/ydd_user/rowInfo", { params: { id } });
      const { username, mobile, sex } = data;
      // 填充数据
      // console.log(username,mobile,sex)
      form.val("form-edit", {
        username: username,
        mobile: mobile,
        sex: sex,
        id: data.id,
      });

      // 上传图片
      $("body").on("click", "#changMsg", function (e) {
        e.preventDefault();
        $("#file").click();
      });
      $("#file").change(async function () {
        // 获取文件信息
        const file = this.files[0];
        const fd = new FormData();
        fd.append("file", file);

        // 发送axios请求上传图片
        const res = await axios.post("/common/upload?type=images", fd, {
          headers: {
            // 更换请求头
            "Content-Type": "multipart/form-data",
            Authorization: "x-token",
          },
        });
        // 将获取的图片的src加到img盒子上显示
        const imgSrc = res.data.data.savePath;
        lscimg = imgSrc
        $(".lsc-box").show();
        $("#lsc-img").attr("src", `http://124.223.14.236:8060/${imgSrc}`);
      });


      // 监听样例开关1的状态变化事件
      form.on("switch(switchTest)", function (data) {
        // 获取开关当前状态，如果开启，将开关名称和对应的值加入表单中
        if (data.elem.checked) {
          $("input[name=sex1]").val("1");
        } else {
          $("input[name=sex1]").val("0");
        }
      });

      // 取表单的值并进行提交
      form.on("submit(formDemo)",async function (data) {
        
        const fd = new FormData(document.querySelector('#form-edit'))
        fd.append('icon',$("#lsc-img").attr('src').substring(26))
        // fd.append('icon',lscimg)
        // 修改一开始内部男女对应数字的bug
        if($('#switchTest').prop('checked')){
          fd.set('sex1','1')
        }
        // 互换sex1与sex的值
        const getsex = fd.get('sex1')
        fd.delete('sex')
        fd.set('sex',getsex)
        fd.delete('sex1')

        // if(fd.get('icon')===''){fd.set('icon',null)}
        
        let num = {}
        fd.forEach(function(value, key) {
          num[key] = value
        });
        // console.log(num)

        const res = await axios.post('/ydd_user/update',num)
        layer.msg('编辑成功')
        layer.close(indexEdit);
        getList()

      });

      // 点击盒子本身取消图片以及盒子隐藏
      $(".lsc-box").click(function () {
        $("#lsc-img").attr("src", "");
        // lscimg=''
        $(this).hide();
      });

      // 点击取消隐藏弹出层
      $("#lsc-close").click(function (e) {
        e.stopPropagation();
        layer.close(indexEdit);
      });
    }

    // 删除
    if (e.target.id === "lj") {
      // 当前删除键的id
      // console.log(e.target.dataset.id)
      // 判断是否确定删除
      if (confirm("确定删除吗")) {
        //
        const id = e.target.dataset.id;
        // 发送axios请求删除数据，并重新渲染页面
        await axios.get(`/ydd_user/del`, { params: { id } });
        alert("删除成功");
        getList();
      }
    }
  });
}
fix();
